import { Ref, useRef, useContext, useState, useEffect } from 'react';
import { Button, Select, Row, Col, Input, Form, DatePicker, Spin, message } from 'antd';
import type { RcFile } from 'antd/es/upload/interface';

import UpdateExpertsUpload from './UpdateExpertsUpload';

import { ExpertsUpdateContext } from '../common/ExpertsContext';
import { ExpertsDictionaryService } from '../services/DictionaryService';
import { ExpertsUpdateService } from '../services/UpdateService';

import { TagSelectNew as TagSelect } from '@/components/TagSelectNew';
import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import pageStyles from '@/common/pageLayout.less';
import { UploadFormCommon } from '@/components/UploadForm';

const TodayDatePicker: any = DatePicker;

const UpdateCounterpartInfoModal: React.FC<ExpertsUpdateAPI.IUpdateCounterpartInfoModal> = ({ form, state, current, onSubmit, onClose }) => {
  const { prefixCls, expertQualifies } = useContext(ExpertsUpdateContext);
  const { attachTypeList } = ExpertsDictionaryService();
  const reloadLayoutRef: Ref<IOneModalRef> = useRef(null);

  const [isShowExpireTime, setIsShowExpireTime] = useState<number>(1);

  // 上传证书接口
  const { uploadExpertsCertificateRun, uploadExpertsCertificateLoading } = ExpertsUpdateService().uploadExpertsCertificateService();

  const changeExpire = (key: string) => {
    setIsShowExpireTime(Number(key));
  };

  // 回显证书信息
  useEffect(() => {
    if (state.operate == 'edit' && expertQualifies.length) {
      console.log(expertQualifies, 'expertQualifies');
      form.setFieldsValue(expertQualifies[current - 1]);
      form.setFieldValue('attachURL', expertQualifies[current - 1]?.attachURL);
      form.setFieldValue('id', expertQualifies[current - 1]?.id);
    }
  }, [current]);

  /**
   * @onSave
   * @description 保存事件
   */
  const onSave = async () => {
    await onSubmit(onCloseModal);
  };

  /**
   * 关闭弹窗
   */
  const onCloseModal = () => {
    if (reloadLayoutRef) {
      if (reloadLayoutRef.current) {
        if (reloadLayoutRef.current.onModalCancel) {
          reloadLayoutRef.current.onModalCancel();
          form.resetFields();
        }
      }
    }
  };

  // 表单证书上传
  // const uploadSuccess = async (file: RcFile) => {
  //   const formData = new FormData();
  //   formData.append('attachFile', file);
  //   const { state, url } = await uploadExpertsCertificateRun(formData);
  //   if (state == 'SUCCESS') {
  //     form.setFieldValue('attachFile', url);
  //   } else {
  //     message.warning('证书上传失败');
  //   }
  // };

  const footerRender = () => {
    return (
      <>
        <Button
          onClick={() => {
            onCloseModal();
          }}
        >
          取消
        </Button>
        <Button type={'primary'} onClick={onSave}>
          确认
        </Button>
      </>
    );
  };

  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={reloadLayoutRef}
        title={state.operate == 'edit' ? '编辑证书' : '添加证书'}
        className={'certificate-info-modal'}
        width={600}
        onCancel={() => {
          onClose(false);
        }}
        footer={footerRender()}
        bodyStyle={{
          padding: '5px 0px',
        }}
        centered
      >
        <Spin spinning={uploadExpertsCertificateLoading}>
          <div className={pageStyles['fromView-styles']}>
            <Row gutter={8} className={`${prefixCls}row`}>
              <Col span={24} className={`${prefixCls}row-col`}>
                <Form form={form}>
                  <Form.Item
                    label="证书类型"
                    name="attachType"
                    rules={[
                      {
                        required: true,
                        message: '请选择证书类型',
                      },
                    ]}
                  >
                    <Select
                      placeholder="请选择证书类型"
                      options={attachTypeList}
                      fieldNames={{
                        label: 'name',
                        value: 'value',
                      }}
                    />
                  </Form.Item>
                  <Form.Item label="证书描述" name="attachContent" rules={[{ required: true, message: '请输入证书描述' }]}>
                    <Input.TextArea placeholder="请输入证件描述" showCount maxLength={200} autoSize={{ minRows: 2, maxRows: 4 }} />
                  </Form.Item>
                  <TagSelect
                    formLabel="是否永久有效"
                    formName="isExpire"
                    radioList={[
                      {
                        value: '1',
                        name: '是',
                      },
                      {
                        value: '0',
                        name: '否',
                      },
                    ]}
                    defalultKeys={1}
                    onChange={changeExpire}
                  />
                  {isShowExpireTime == 0 && (
                    <>
                      <Col span={12}>
                        <Form.Item label="有效期开始" name="expireStartTime" rules={[{ required: true, message: '请选择有效期开始时间' }]}>
                          <TodayDatePicker placeholder="请选择有效期开始时间" style={{ width: '100%' }} format="YYYY-MM-DD" />
                        </Form.Item>
                      </Col>
                      <Col span={12}>
                        <Form.Item label="有效期结束" name="expireEndTime" rules={[{ required: true, message: '请选择有效期结束时间' }]}>
                          <TodayDatePicker placeholder="请选择有效期结束时间" style={{ width: '100%' }} format="YYYY-MM-DD" />
                        </Form.Item>
                      </Col>
                    </>
                  )}
                  {/* <Form.Item label="证书图片" name="attachFile" rules={[{ required: true, message: '请上传证书' }]}>
                    <UpdateExpertsUpload desc={'选择证书图片'} width={750} uploadSuccess={uploadSuccess} />
                  </Form.Item> */}
                  <UploadFormCommon
                    form={form}
                    label="上传图片"
                    fileFormName={'attachURL'}
                    spanCol={24}
                    inRowProportion={24}
                    name={'attachFile'}
                    required={true}
                    accept={'.jpg|.jpeg|.png'}
                    url={'/expertInfoController/uploadFile'}
                    downloadUrl={'/expertInfoController/downloadFile'}
                    fileFormDelName={'delAttachURL'}
                    maxFile={1}
                    defaultFiles={state.operate == 'edit' ? expertQualifies[current - 1]?.attachURL || null : null}
                    uploadSuccessCallback={(attachPaths) => {
                      form.setFieldValue('attachURL', attachPaths);
                    }}
                    delFunc={function (delFilePath: string, attachmentPath: any): void {
                      form.setFieldValue('delAttachURL', delFilePath);
                    }}
                    hintTitle={'且只能上传 1 个！'}
                    fieldBusiPath={'expert/info'}
                  >
                    上传
                  </UploadFormCommon>
                </Form>
              </Col>
            </Row>
          </div>
        </Spin>
      </OneModal>
    </>
  );
};

export default UpdateCounterpartInfoModal;
